package com.bawei.module_home

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_base.RoutePath
import com.bawei.lib_common.cache.RecyclerCachePool
import com.bawei.lib_common.mvi.BaseMviFragment
import com.bawei.module_home.adapter.HomeListAdapter
import com.bawei.module_home.adapter.PlayListAdapter
import com.bawei.module_home.cache.HomeItemCache
import com.bawei.module_home.databinding.FragmentHomeListBinding
import com.bawei.module_home.entriy.CommendEntity
import com.bawei.module_home.entriy.CommentHolder
import com.bawei.module_home.entriy.CommentListEntriyItem
import com.bawei.module_home.entriy.SimpleVideoEntity
import com.bawei.module_home.intent.HomeViewIntent
import com.bawei.module_home.state.HomeUiState
import com.bawei.module_home.view.CommentDialogFragment
import com.bawei.module_home.vm.HomeViewmodel
import com.bawei.module_play.entriy.CommentEntriyItem
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class HomeListFragment : BaseMviFragment<FragmentHomeListBinding>() {

    private val mViewModel:HomeViewmodel by activityViewModels()
    private var typeId=0
    private var channelId=""
    private var pageIndex=1
    private var pagesize=10
    private var simpVideoList= mutableListOf<SimpleVideoEntity>()
    private lateinit var videolistadapter:HomeListAdapter
    var itemCache : HomeItemCache?=null
    var posion:String=""



    companion object{
        @JvmStatic
        fun newInstance(channelId:String,typeId:Int)=HomeListFragment().apply {
            arguments=Bundle().apply {
                putString("channelId",channelId)
                putInt("typeId",typeId)
            }
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_home_list
    }

    override fun initViews() {
        //获取传递进来的参数
        arguments?.let {
            channelId=it.getString("channelId").toString()
            typeId=it.getInt("typeId")
        }

        //下来刷新事件
        mDatatBinding.refreshLayout.setOnRefreshListener {
            if (simpVideoList.size ==0 || pageIndex > 1){
                pageIndex=1
                loadData()
            }

        }



       videolistadapter= HomeListAdapter(simpVideoList).apply {
           itemCache= HomeItemCache()
           preloadEndCount=4
           preloadMoreData={
                   pageIndex += 1
                   loadData()
           }
           setOnItemClickListener(object :HomeListAdapter.OnItemClickListener{
               override fun onItemChick(v: View, position: Int) {
                   when(v.id){
                       R.id.tv_title -> {
                           ARouter.getInstance().build(RoutePath.PATH_PLAY_PAGE)
                               .withString("videoPath", simpVideoList[position].videopath)
                               .withString("userId", simpVideoList[position].userid)
                               .withInt("typeId", typeId)
                               .withString("channelId", channelId)
                               .withString("itemId",  simpVideoList[position].item_id)
                               .withInt("moduleType", 0)
                               .withString("title", simpVideoList[position].title)
                               .navigation()
                       }
                       R.id.iv_commend -> {
                           posion=simpVideoList[position].item_id
                           val dialog=CommentDialogFragment()
                           dialog.show(requireActivity().supportFragmentManager,"")

                       }
                       R.id.iv_more-> {
                           this@HomeListFragment.showToastMsg("正在开发，敬请期待！")
                       }
                   }
               }

           })
       }
        mDatatBinding.rvVideoList.run {
            //设置屏幕外缓存ViewHolder的数量，默认为2
            setItemViewCacheSize(12)
          //防止Item组件重复测量（适用于大小固定子组件）
            setHasFixedSize(true)
          //设置缓存池大小
            setRecycledViewPool(RecyclerCachePool)

            //添加滚动事件处理图片加载
            addOnScrollListener(object :OnScrollListener(){
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if(newState==RecyclerView.SCROLL_STATE_IDLE){
                        //恢复图片加载
                        Glide.with(this@HomeListFragment).resumeRequests()
                    }else{
                        //暂停图片加载
                        Glide.with(this@HomeListFragment).pauseRequests()
                    }
                }
            })

            //关闭不必要的动画
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations=false

            adapter=videolistadapter
            layoutManager=LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        }



    }
    override fun onDestroyView() {
        itemCache?.clearChche()
        super.onDestroyView()

    }

    override suspend fun sendViewIntent() {
        super.sendViewIntent()
        mViewModel.channel.send((HomeViewIntent.LoadVideoCommentList(posion,0)))
    }




    private fun loadData() {
        lifecycleScope.launch {
            if(typeId==-1){
                mViewModel.channel.send((HomeViewIntent.LoadRecommendSimpleVideoList(pageIndex,pagesize)))
            }else{
                mViewModel.channel.send((HomeViewIntent.LoadSimpleVideoList(channelId,pageIndex,pagesize)))
            }
        }
    }

    fun lazyLoadData(){
        //如果数据类型与传递进来的channelId不一致，需要清理掉后再加载
        if (simpVideoList.size > 0 && simpVideoList[0].channelid != channelId){
            simpVideoList.clear()
            videolistadapter.notifyDataSetChanged()
        }
        loadData()

    }

    override suspend fun collectUIState() {
        mViewModel.uiStateFlow.collect{
            when(it){
                is HomeUiState.LoadSimpleVideoSuccess -> updatePageData(it.list)
                is HomeUiState.LoadSimpleVideoFail -> {
                    //回退到上一页
                    if (pageIndex > 1){
                        pageIndex -= 1
                    } else {
                        mDatatBinding.refreshLayout.finishRefresh()
                        simpVideoList.clear()
                        videolistadapter.notifyDataSetChanged()
                    }
                }

                is HomeUiState.LoadVideoCommentSuccess->{
                    CommentHolder.data=it.list
                }
                is HomeUiState.LoadVideoCommentFail->{

                }
                else -> {}
            }
        }
    }

    private fun updatePageData(list: List<SimpleVideoEntity>) {
        //如果下拉刷新获取第一页，需要清理
        if (pageIndex == 1){
            mDatatBinding.refreshLayout.finishRefresh()
            simpVideoList.clear()
        }
        simpVideoList.addAll(list)
        videolistadapter.notifyDataSetChanged()
    }




}